package bulkyshare.project.de.bulkyshare.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

import bulkyshare.project.de.bulkyshare.R;
import bulkyshare.project.de.bulkyshare.container.Contact;

/**
 * @author Alexander Radtke
 * @version 1.0
 *
 *
 */
public class ContactListDialog extends Dialog implements AdapterView.OnItemClickListener {
    private Activity activity;
    private String type;
    private ArrayList<Contact> contacts;
    private ListView contact_list;
    private ArrayAdapter<String> contact_adapter;

    public ContactListDialog(Activity activity, String type, ArrayList<Contact> contacts) {
        super(activity);
        this.activity = activity;
        this.type = type;
        this.contacts = contacts;
    }

    @Override
    public void onCreate(Bundle onSavedInstanceState) {
        super.onCreate(onSavedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.contact_list_dialog);
        ArrayList<String> values = new ArrayList<String>();
        for (int i = 0; i < contacts.size(); i++) {
            values.add(contacts.get(i).getContact());
        }

        contact_list = (ListView) findViewById(R.id.contact_list);
        contact_adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, values);
        contact_list.setAdapter(contact_adapter);
        contact_list.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView adapterView, View view, int pos, long id) {
        // If the "contact by mail" button was pressed and the user selected a mail address
        // from the ListView start a new mail intent
        if (type.equals("mail")) {
            Intent mail = new Intent(Intent.ACTION_SEND);
            // Set all the data for a mail
            mail.setType("message/rfc822");
            mail.putExtra(Intent.EXTRA_EMAIL, new String[]{contacts.get(pos).getContact()});
            mail.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.mail_subject));
            mail.putExtra(Intent.EXTRA_TEXT, activity.getString(R.string.mail_content));
            activity.startActivity(mail);
            dismiss();
        // If the "contact by phone" button was pressed and the user selected a phone number
        // from the ListView start a new phone intent
        } else {
            Intent phone = new Intent(Intent.ACTION_DIAL);
            phone.setData(Uri.parse("tel:" + contacts.get(pos).getContact()));
            activity.startActivity(phone);
            dismiss();
        }
    }
}
